<template>
  <div class="app-container user-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search_val" placeholder="搜索会员" style="width: 330px;margin-right: 10px;" @keyup.enter.native="handleFilter">
        <el-select slot="prepend" v-model="listQuery.search_key" placeholder="请选择">
          <template v-for="item in searchKeys">
            <el-option v-if="!(item.val === 'num' && listQuery.type === 'send')" :key="item.val" :label="item.label" :value="item.val" />
          </template>
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
      <el-radio-group v-model="listQuery.type" v-permission="['admin', 'cashier']" @change="handleFilter">
        <el-radio label="buy">购买人</el-radio>
        <el-radio label="send">送货人</el-radio>
      </el-radio-group>
      <el-dropdown v-if="envRole === 'sub'" v-permission="['admin', 'cashier']" @command="handleAdd">
        <el-button type="primary" icon="el-icon-plus">
          添加会员<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="buy">购买人</el-dropdown-item>
          <el-dropdown-item command="send">送货人</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button v-permission="['editor']" type="primary" icon="el-icon-plus" @click="handleAdd('send')">添加送货人</el-button>
    </div>
    <el-table
      key="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      @cell-click="handleRemark"
    >
      <el-table-column v-if="listQuery.type === 'buy'" key="buy_num" align="center" label="号牌" prop="buy.num" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.buy.num">{{ scope.row.buy.num }}</span>
          <el-button v-else size="mini" type="primary" @click="handleBind(scope.row)">绑定</el-button>
        </template>
      </el-table-column>
      <el-table-column v-else key="send_id" align="center" label="ID" prop="base.id" width="60" />
      <el-table-column key="base_name" align="center" label="姓名" prop="base.name" width="80" />
      <el-table-column key="base_tel1" align="center" label="电话" prop="base.tel1" width="120" />
      <el-table-column key="base_idcard" align="center" label="身份证" prop="base.idcard" width="170" />
      <!-- 购买人 -->
      <template v-if="listQuery.type === 'buy'">
        <el-table-column key="buy_buy_level" align="center" label="购买力等级" prop="buy.buy_level" width="100" />
        <el-table-column key="buy_credit_level" align="center" label="信用等级" prop="buy.credit_level" width="90" />
        <el-table-column key="buy_judg_level" align="center" label="判断力等级" prop="buy.judg_level" width="100" />
        <el-table-column key="buy_fee_rate" align="center" label="手续费率" prop="buy.fee_rate" width="80" :formatter="formatFeeRate" />
        <el-table-column key="buy_remark" align="center" show-overflow-tooltip label="备注(点击修改)" prop="buy.remark" width="220">
          <template slot-scope="scope">
            {{ scope.row.buy.remark || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="保证金" width="90">
          <template slot-scope="scope">
            <b style="color: green">{{ scope.row.buy.money }}</b>
          </template>
        </el-table-column>
        <el-table-column v-if="listQuery.type === 'buy' && envRole === 'sub'" v-permission="['admin', 'cashier']" fixed="right" align="center" label="保证金" width="90">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" @click="handleMoney(scope.row, 'change')">修改</el-button>
              <!-- <el-button v-if="scope.row.buy.mstate === 2" size="mini" type="warning" @click="handleMoney(scope.row, 'withdraw')">提现</el-button> -->
            </el-button-group>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="VIP" width="90">
          <template slot-scope="scope">
            <el-button v-if="scope.row.buy.mstate === 0" size="mini" type="primary" @click="handleVIP(scope.row, 1)">设置VIP</el-button>
            <el-button v-else size="mini" type="warning" @click="handleVIP(scope.row, 0)">取消VIP</el-button>
          </template>
        </el-table-column>
      </template>
      <!-- 送货人 -->
      <template v-else>
        <el-table-column key="send_number" align="center" label="编号" prop="send.number" width="70" />
        <!-- <el-table-column align="center" label="图录费" prop="send.catafee" width="100" /> -->
        <el-table-column key="send_send_level" align="center" label="送货量等级" prop="send.send_level" width="100" />
        <el-table-column key="send_deal_level" align="center" label="成交率等级" prop="send.deal_level" width="100" />
        <el-table-column key="send_deal_point" align="center" label="成交量积分" prop="send.deal_point" width="100" />
        <el-table-column key="send_fee_rate" align="center" label="手续费率" prop="send.fee_rate" width="80" :formatter="formatFeeRate" />
        <el-table-column key="send_remark" align="center" show-overflow-tooltip label="备注(点击修改)" prop="send.remark" width="200">
          <template slot-scope="scope">
            {{ scope.row.send.remark || '暂无' }}
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" align="center" label="详细信息" width="90">
        <template slot-scope="scope">
          <!-- <el-button type="text" @click="handleDetail(scope.row, 'view')">查看</el-button>
          <el-button type="text" @click="handleDetail(scope.row, 'edit')">编辑</el-button> -->
          <el-button size="mini" type="warning" @click="handleDetail(scope.row, 'edit')">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="total > 0" class="pagination-container">
      <el-pagination background :current-page="listQuery.page" :page-sizes="[15, 20, 30]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 用户信息 -->
    <el-dialog
      :title="`${titleMap[userInfoMode]}${titleMap[userInfoType]}信息`"
      fullscreen
      center
      :visible.sync="dialogInfoVisible"
      @closed="handleDialogClose"
    >
      <user-info
        ref="userInfo"
        :mode="userInfoMode"
        :type="userInfoType"
        :data="currUser"
        :btn-loading="saveLoading"
        @close="dialogInfoVisible = false"
        @submit="handleSubmit"
      />
    </el-dialog>

    <!-- 保证金 -->
    <el-dialog :title="titleMap[diaMoneyState]" center :visible.sync="dialogMoneyVisible">
      <el-form ref="moneyForm" :model="moneyTemp" label-position="left" label-width="100px">
        <el-form-item label="保证金额" prop="money">
          <el-input v-model.trim="moneyTemp.money" :disabled="diaMoneyState === 'withdraw'" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="moneyTemp.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMoneyVisible = false">取消</el-button>
        <el-button v-if="diaMoneyState === 'change'" :loading="saveLoading" type="primary" @click="updateMoney">保存</el-button>
        <el-button v-if="diaMoneyState === 'withdraw'" :loading="saveLoading" type="primary" @click="handleWithdraw">确认提现</el-button>
      </div>
    </el-dialog>

    <!-- 绑定密钥 -->
    <el-dialog title="绑定号牌" width="30%" center :visible.sync="dialogBindVisible">
      <el-form ref="bindForm" :model="bindTemp" :rules="bindRules" label-position="left" label-width="80px">
        <el-form-item label="号牌" prop="num">
          <el-input v-model.trim="bindTemp.num" />
        </el-form-item>
        <el-form-item label="密钥" prop="key">
          <el-input v-model.trim="bindTemp.key" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBindVisible = false">取消</el-button>
        <el-button :loading="saveLoading" type="primary" @click="bindNum">绑定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserInfo from './components/UserInfo'
import { getUsers, getUsersBySub, bindKey, updateUser, setRemark, setMoney, setVIPState, withdraw } from '@/api/user'

export default {
  components: { UserInfo },
  data () {
    return {
      listQuery: {
        page: 1,
        limit: 15,
        type: 'buy', // buy send
        search_key: 'num',
        search_val: '',
        subid: null
      },
      list: [],
      total: 0,
      listLoading: true,
      searchKeys: [
        { label: '身份证', val: 'idcard' },
        { label: '号牌', val: 'num' },
        { label: '手机号', val: 'tel' }
      ],
      dialogInfoVisible: false,
      userInfoMode: '', // edit add view
      userInfoType: '', // buy send
      currUser: null,
      titleMap: {
        edit: '修改',
        add: '添加',
        view: '查看',
        buy: '购买人',
        send: '送货人',
        change: '修改保证金额数',
        withdraw: '确认完成提现'
      },
      saveLoading: false,
      dialogMoneyVisible: false,
      diaMoneyState: '', // change  withdraw
      moneyTemp: {},
      dialogBindVisible: false,
      bindTemp: {
        id: '',
        subid: '',
        num: '',
        key: ''
      },
      bindRules: {
        num: [{ required: true, message: '号牌不能为空', trigger: 'blur' }],
        key: [{ required: true, message: '密钥不能为空', trigger: 'blur' }]
      },
      envRole: process.env.VUE_APP_ROLE
    }
  },
  computed: {
    roles () {
      return this.$store.getters.roles
    }
  },
  created () {
    if (this.$route.params.subid) {
      this.listQuery.subid = this.$route.params.subid
    }
    if (this.roles.includes('editor')) {
      this.listQuery.type = 'send'
      this.listQuery.search_key = this.searchKeys[0].val
    }
    this.fetchData()
  },
  methods: {
    fetchData () {
      const fetchUsers = this.envRole === 'super' ? getUsersBySub : getUsers
      this.listLoading = true
      fetchUsers(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },

    handleBind (row) {
      this.bindTemp = {
        id: row.base.id,
        subid: row.buy.subid,
        num: '',
        key: ''
      }
      this.dialogBindVisible = true
      this.$nextTick(() => {
        this.$refs['bindForm'].clearValidate()
      })
    },

    bindNum () {
      this.$refs['bindForm'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          bindKey(this.bindTemp).then(res => {
            this.saveLoading = false
            this.fetchData()
            this.$message.success('绑定成功')
            this.dialogBindVisible = false
          }).catch(err => {
            this.saveLoading = false
            console.log(err)
          })
        }
      })
    },

    handleAdd (command) {
      this.userInfoType = command
      this.userInfoMode = 'add'
      this.dialogInfoVisible = true
      this.$nextTick(() => {
        this.currUser = JSON.parse(JSON.stringify(this.$refs.userInfo.form))
      })
    },

    handleDetail (row, mode) {
      var curr = JSON.parse(JSON.stringify(row))
      const type = this.listQuery.type
      const isNum = typeof curr[type].fee_rate === 'number'
      curr[type].fee_rate = isNum ? curr[type].fee_rate * 10000 / 100 : curr[type].fee_rate
      if (type === 'buy') {
        curr.buy.num_bak = curr.buy.num
        curr.buy.key = ''
      }
      this.currUser = curr
      this.userInfoType = type
      this.userInfoMode = mode
      this.dialogInfoVisible = true
    },

    handleSubmit (formData) {
      this.saveLoading = true
      updateUser(formData).then(res => {
        this.saveLoading = false
        this.dialogInfoVisible = false
        this.listQuery.type = this.userInfoType
        this.listQuery.page = 1
        this.fetchData()
        this.$message.success(res.msg)
      }).catch(err => {
        console.log(err)
        this.saveLoading = false
      })
    },

    handleDialogClose () {
      this.$refs.userInfo.$refs['form'].clearValidate()
      this.$refs.userInfo.$refs['uploader'].clearFiles()
      this.$refs.userInfo.formData = new FormData()
    },

    handleRemark (row, column) {
      if (column.property === 'buy.remark' || column.property === 'send.remark') {
        this.$prompt('', '编辑备注', {
          confirmButtonText: '保存',
          cancelButtonText: '关闭',
          inputValue: row[this.listQuery.type].remark,
          inputType: 'textarea',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              var postdata = {
                id: row[this.listQuery.type].id,
                remark: instance.inputValue,
                type: this.listQuery.type
              }
              setRemark(postdata).then(res => {
                done()
                instance.confirmButtonLoading = false
                this.fetchData()
              }).catch(err => {
                console.log(err)
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    handleMoney (row, op) {
      this.dialogMoneyVisible = true
      this.diaMoneyState = op
      this.moneyTemp = { id: row.buy.id, money: row.buy.money, remark: row.buy.remark }
      this.$nextTick(() => {
        this.$refs['moneyForm'].clearValidate()
      })
    },
    updateMoney () {
      this.$refs['moneyForm'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          setMoney(this.moneyTemp).then(res => {
            this.saveLoading = false
            this.fetchData()
            this.$message.success(res.msg)
            this.dialogMoneyVisible = false
          }).catch(err => {
            console.log(err)
            this.saveLoading = false
          })
        }
      })
    },
    handleWithdraw () {
      this.$confirm('确认已经完成该用户的提现?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        this.saveLoading = true
        const data = { id: this.moneyTemp.id, remark: this.moneyTemp.remark }
        withdraw(data).then(res => {
          this.listLoading = false
          this.saveLoading = false
          this.dialogMoneyVisible = false
          this.fetchData()
          this.$notify({
            message: res.msg,
            type: 'success',
            duration: 2000
          })
        }).catch(err => {
          this.saveLoading = false
          this.listLoading = false
          console.log(err)
        })
      }).catch(() => {})
    },

    handleVIP (row, targerMState) {
      this.$confirm('确定要执行此操作吗？', {
        closeOnClickModal: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            const data = {
              id: row.buy.id,
              subid: row.buy.subid,
              mstate: targerMState
            }
            setVIPState(data).then(res => {
              done()
              instance.confirmButtonLoading = false
              this.fetchData()
              this.$message.success(res.msg)
            }).catch(err => {
              console.log(err)
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).catch(() => {})
    },

    formatFeeRate (row, column, cell) {
      return cell !== '' ? cell * 10000 / 100 + '%' : cell
    },
    handleFilter () {
      if (this.listQuery.type === 'send' && this.listQuery.search_key === 'num') {
        this.listQuery.search_key = 'idcard'
      }
      this.listQuery.page = 1
      this.fetchData()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.fetchData()
    }
  }
}
</script>
<style lang="scss" scoped>
.user-container {
  .el-table {
    margin-bottom: 15px;
    .el-button--text {
      padding: 0;
      &:last-of-type {
        color: #E6A23C;
      }
    }
  }
}
</style>
